#include "tcpserver.h"
#include "tcpconnection.h"
#include "acceptor.h"
#include <memory>
#include <string>

TcpServer::TcpServer(EventLoop* loop, const std::string& ip, uint16_t port) 
: loop_(loop), acceptor_(std::make_unique<Acceptor>(loop, ip, port)), nextConnId_(1){
    acceptor_->setNewConnectionCallback([this](int sockfd, const std::string& peerAddr){
        this->newConnection(sockfd, peerAddr);
    });
}

TcpServer::~TcpServer(){
    for (auto& [fd, conn] : connections_) {
        conn->shutdown();
    }
}

void TcpServer::start(){
    acceptor_->listen();
}

void TcpServer::newConnection(int sockfd, const std::string& peerAddr){
    std::string connName = "conn#" + std::to_string(nextConnId_++);
    std::shared_ptr<TcpConnection> conn = std::make_shared<TcpConnection>(loop_, sockfd, peerAddr);

    conn->setConnectionCallback(connectionCallback_);
    conn->setMessageCallback(messageCallback_);
    conn->setCloseCallback([this](const std::shared_ptr<TcpConnection>& connection) {
        connections_.erase(connection->getSockfd());
    });

    connections_[sockfd] = conn;

    if (connectionCallback_) {
        connectionCallback_(conn);
    }
}